<?php
/**
 * Object Relational Persistence Mapping Class for table: service_room
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */
class ServiceRoom extends ORDataObject {

	/**#@+
	 * Fields of table: service_room mapped to class members
	 */
	var $service_room_id		= 	'';
	var $service_id				= 	'';
	var $room_id				= 	'';
	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'service_room';

	/**
	 * Primary Key
	 */
	var $_key = 'service_room_id';
	
	/**
	 * Internal Name
	 */
	var $_internalName = 'ServiceRoom';

	/**
	 * Handle instantiation
	 */
	function ServiceRoom() {
		parent::ORDataObject();
	}
	
	public function getRoomsOfService($serviceId) {
		$field		=	L10nHelper::changeField(L10nHelper::getLocale(), 'name');
		
		$ds = new Datasource_sql();
		$sql = array (
			'cols'	=> "r.room_id, r.$field name",
			'from'		=> "$this->_table sr INNER JOIN room r ON sr.room_id = r.room_id",
			'where'		=> "sr.service_id = $serviceId",
			'orderby'	=> "name"
			);		
		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}
	
	public function addItem($roomArr, $servId) {
		$firstServiceRoomId = 0;
		 foreach ($roomArr as $roomId) {
		 	$o = Celini::newORDO('ServiceRoom');
		 	$o->populateArray(array(
		 					'service_id'	=> $servId,
		 					'room_id'	=> $roomId));
		 	$o->persist();
		 	if ($firstServiceRoomId == 0) {
		 		$firstServiceRoomId = $o->get_id();
		 	}		 			 	
		 }
		 return $firstServiceRoomId; 
	}
	
	public function updateItem($roomArr, $servId) {
		// get old service_room_id to update services of packages
		$ds = new Datasource_sql();
		$sql = array (
			'cols'	=> "service_room_id",
			'from'		=> "$this->_table",
			'where'		=> "service_id = $servId"			
			);		
		$ds->setup($this->_db, $sql);
		$srArray = $ds->toArray('service_room_id');
		
		
		 $sql = "delete from service_room where service_id = $servId";
		 $this->_execute($sql);
		 $newId = $this->addItem($roomArr, $servId);
		 		 
		 foreach ($srArray as $oldId) {
		 	$sql = "update package_service_item set service_room_id = $newId where service_room_id = $oldId";
		 	$this->_execute($sql); 
		 }
		 
	}
	
	public function deleteService($serviceId) {
		$sql = "delete from service_room where service_id = $serviceId";
		$this->_execute($sql);
	}
	
}
?>
